//203. 移除链表元素

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val){
  struct ListNode*p=head;
  struct ListNode*pre=NULL;
  struct ListNode*ps=head;
  while(1)
  {
    while(p)
    {
      if(p->val==val)
      {
        break;
      }
      pre=p;
      p=p->next;
    }
    if(p==NULL)
      return head;
    ps=p->next;
    if(p==head)
    {
      head=p->next;
      p->next=NULL;
      free(p);
    }
    else if(p->next==NULL)
    {
      pre->next=NULL;
      free(p);
    }
    else
    {
      pre->next=p->next;
      p->next=NULL;
      free(p);
    }
    p=ps;
  }
  return head;
}